<?php

namespace App\Http\Controllers\Home;

use App\Models\Admin\Weibo;
use App\Models\Home\Comment;
use App\Models\Home\Photo;
use App\Models\Home\UserInfo;
use App\Models\RTresult;
use App\Models\TempEmail;
use App\Models\TempPhone;
use App\Models\Home\User;
use App\Tool\SMS\SendTemplateSMS;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;

class IndexController extends Controller
{
    //getHash
    public function getHash($psw)
    {
        return Hash::make($psw);
    }

    //通过路由到达注册视图
    public function register()
    {

        return view('home.register');
    }

    //发送注册页面的手机短信验证码
    public function sendSMS(Request $request)
    {
        //获取返回的数据对象
        $rt_result = new RTresult();
        //获取手机号
        $phone = $request->phone;
        //判断手机号是否是为空
        if ($phone == '') {
            $rt_result->status = 1;
            $rt_result->message = '手机号不能为空';
            return $rt_result->toJson();
        }
        //定义随机因子
        $charset = '1234567890';
        $phoneMsg = new SendTemplateSMS();
        //随机得到随机因子
        $code = '';
        $len = strlen($charset);
        for ($i = 0; $i < 4; $i++) {
            $code .= $charset{mt_rand(0, strlen($len))};
        }
        $rt_result = $phoneMsg->send($phone, array($code, 60), 1);
        if ($rt_result->status == 0) {
            //获取tmp_phone表模型
            $phone_temp = new TempPhone();
            $phone_temp->phone = $phone;
            $phone_temp->code = $code;
            $phone_temp->deadline = time() + 5 * 60;
            $phone_temp->save();
        }
        return $rt_result->toJson();
    }

    //发送注册页面的邮箱验证码
    public function sendRegcode(Request $request)
    {
        $rt_result = new RTresult();

        //获取填写的邮箱
        $email = $request->user;
        //查询邮箱是否已注册
        $result = User::where('email', $email)->first();
        //如果已存在
        if ($result) {
            $rt_result->status = 0;
            $rt_result->message = '账号已存在';
            return $rt_result->toJson();
        }
        //如果未注册，生成6位数字随机码发送过去
        $str = md5(random_int(0, time()));
        //获取字符串的长度
        $length = strlen($str) - 1;
        //字符串截取长度
        $count = 6;
        //字符串截取开始位置
        $start = rand(0, $length - $count);
        //随机截取字符串，取其中的一部分字符串
        $code = substr($str, $start, $count);

        //将随机码通过邮件发送到用户邮箱
        Mail::raw('您的注册验证码为' . $code . '有效期5分钟',
            function ($message) use ($email) {
                $message->to($email)->subject('osdoc注册验证码');
            });
        //发送成功后
        $rt_result->status = 1;
        $rt_result->message = '邮件发送成功，请查收';
        //将验证码存入数据库以备验证
        $email_temp = new TempEmail();
        $email_temp->email = $email;
        $email_temp->code = $code;
        $email_temp->deadline = time() + 5 * 60;
        $email_temp->save();
        return $rt_result->toJson();
    }

    //用户注册添加用户信息到数据库
    public function addUser(Request $request)
    {
        //获取用户信息
        $username = $request->user;
        $password = $request->password;
        $confirm = $request->confirm;
        $code = $request->code;
        $rt_result = new RTresult();
        //判断两次密码是否一致
        if ($password != $confirm) {
            $rt_result->status = 2;
            $rt_result->message = "两次输入的密码不一致";
            return $rt_result->toJson();
        } else {
            //判断用户名是手机号码还是邮箱
            $preg1 = "/^1[34578]\d{9}$/";
            $preg2 = "/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/";
            $match1 = preg_match($preg1, $username);
            $match2 = preg_match($preg2, $username);
            //如果既不是手机也不是邮箱
            if (!$match1 && !$match2) {
                return back()->with('fails', '手机号|邮箱格式不正确');
            } elseif ($match1) {
                //如果是手机，从手机验证码表中取出验证码
                $code_db = TempPhone::get()->where('phone', $username)->last();
                //从用户表中取出用户
                $users = User::where('phone', $username)->get()->first();
                //判断验证码是否正确或者过期,判断手机号是否已经注册
                if ($users) {
                    //判断手机号是否已被注册
                    $rt_result->status = 1;
                    $rt_result->message = "手机号已被注册";
                    return $rt_result->toJson();
                } elseif ($code != $code_db->code) {
                    //判断验证码是否正确
                    $rt_result->status = 1;
                    $rt_result->message = "验证码错误";
                    return $rt_result->toJson();
                } elseif ($code_db->deadline < time()) {
                    //判断验证码是否过期
                    $rt_result->status = 1;
                    $rt_result->message = "验证码已过期";
                    return $rt_result->toJson();
                } else {
                	$user_info = new UserInfo();
            		$user = new User();
                    //将注册信息存入数据库
                    $user->phone = $username;
                    $user->password = Hash::make($password);
                    $user->created_at = getTimeFormat();
                    $user->save();
                    //dd($user->id);
                    //$user_id=$user->where('phone',$username)->first()->id;
                    //dd($user_id);
                    $user_info->user_id = $user->id;
                    $user_info->nickname = randomNickname();
                    $user_info->avatar = '/images/80x80.png';
                    $user_info->bgd = 'images/background/4.jpeg';
                    $user_info->address = '0,0,0';
                    $user_info->save();
                    $rt_result->status = 0;
                    $rt_result->message = "注册成功";
                    return $rt_result->toJson();
                }
            } elseif ($match2) {
            	$user_info = new UserInfo();
            	$user = new User();
                //如果是邮箱，从邮箱验证码表中取出验证码
                $code_db = TempEmail::get()->where('email', $username)->last();
                //从用户表中取出用户邮箱
                $emails = User::where('email', $username)->get()->first();
                //判断验证码是否正确或者过期,判断邮箱是否已经注册
                if ($emails) {
                    //判断邮箱是否已被注册
                    $rt_result->status = 1;
                    $rt_result->message = "手机号已被注册";
                    return $rt_result->toJson();
                } elseif ($code != $code_db->code) {
                    //判断验证码是否正确
                    $rt_result->status = 1;
                    $rt_result->message = "验证码错误";
                    return $rt_result->toJson();
                } elseif ($code_db->deadline < time()) {
                    //判断验证码是否过期
                    $rt_result->status = 1;
                    $rt_result->message = "验证码已过期";
                    return $rt_result->toJson();
                } else {
                	$user_info = new UserInfo();
                	$user = new User();
                    //将注册信息存入数据库
                    $user->email = $username;
                    $user->password = Hash::make($request->password);
                    $user->created_at = getTimeFormat();
                    $user->save();
                    $user_info->user_id = $user->id;
                    $user_info->nickname = randomNickname();
                    $user_info->avatar = '/images/80x80.png';
                    $user_info->bgd = 'images/background/4.jpeg';
                    $user_info->address = '0,0,0';
                    $user_info->save();
                    $rt_result->status = 0;
                    $rt_result->message = "注册成功";
                    return $rt_result->toJson();
                }
            }
        }
    }

    //前台用户登录
    public function doLogin(Request $request)
    {
        if ($request->isMethod('post')) {

            $rules = ['user' => 'required',
                'password' => 'required',
                'captcha' => 'required|captcha'];

            $msg = ['required' => ':attribute为必填项',
                'captcha' => ':attribute不正确'];

            $chinese = ['phone' => '手机号|邮箱',
                'password' => '密码',
                'captcha' => '验证码',
            ];
            //进行格式验证
            $validator = Validator::make($request->all(), $rules, $msg, $chinese);
            if ($validator->fails()) {
                //如果格式验证失败
                return redirect()->back()->withErrors($validator);
            } else {
                //如果格式验证通过
                //获取传递过来的数据
                $user = $request->user;
                $password = $request->password;
                //判断是手机还是邮箱
                $preg1 = "/^1[34578]\d{9}$/";
                $preg2 = "/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/";
                $match1 = preg_match($preg1, $user);
                $match2 = preg_match($preg2, $user);
                //既不是手机也不是邮箱
                if (!$match1 && !$match2) {
                    return back()->with('fails', '手机号|邮箱格式不正确');
                } elseif ($match1) {
                    //如果是手机，从user表中取出密码
                    $res = User::where('phone', $user)->first();
                } elseif ($match2) {
                    //如果是邮箱，则连接查询出user表中的密码
                    $res = User::where('email', $user)->first();
                }
                //如果该用户存在
                if ($res) {
                    $password_db = $res->password;
                    //进行密码匹配
                    if (Hash::check($password, $password_db)) {
                        //判断是否允许登录
                        if ($res->is_allowed) {
                            //登录成功将用户信息保存到session中
                            $user_id = $res->id;
                            //获取个人详情
                            $info = User::join('user_infos', 'users.id', '=', 'user_infos.user_id')
                                ->select('users.*', 'user_infos.*')
                                ->where('users.id', $user_id)
                                ->get()->first();
                                //dd($info);
                            //获取头像，如果没有头像，则给用户默认头像
                            $photo = UserInfo::where('user_id', $user_id)->select('avatar')->first();
                            if ($photo == null) {
                                $avatar = '/images/80x80.png';
                            } else {
                                $avatar = $info->avatar;
                            }
                            //获取背景图片，如果没有，给用户默认背景
                            if ($info->bgd == null) {
                                $bgd = '/images/background/4.jpeg';
                            } else {
                                $bgd = $info->bgd;
                            }
                            //将信息存入session
                            Session::put('user.id', $info->user_id);
                            Session::put('user.phone', $info->phone);
                            Session::put('user.nickname', $info->nickname);
                            Session::put('user.avatar', $avatar);
                            Session::put('user.bgd', $bgd);
                            Session::save();
                            //将数据返回视图
                            return redirect('/');
                        } else {
                            return back()->with('fails', '该用户不被允许登录');
                        }
                    } else {
                        //如果密码不匹配
                        return back()->with('fails', '用户名密码不匹配');
                    }
                } else {
                    //如果该用户不存在
                    return back()->with('fails', '用户名密码不匹配');
                }
            }
        }else{
            //如果是其他请求方式
            return redirect('/login');
        }
    }

    public function logout()
    {
        //清空用户信息
        Session::flush();
        return redirect(url('/'));
    }
}